<template>
    <div class="content">
        <TableLayout form-title="">
        <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" class="formInline" :rules="rules" ref="formInline" label-width="90px"  slot="form">          
                <el-row :gutter="41">
                    <el-col :span="8" v-if="schoolType == '0'"> 
                        <el-form-item label="年级" prop="gradeId">
                         <grade v-model="formInline.gradeId"
                            :isDefaultFill='true' 
                            @defaultFillGrade='defaultFillGrade'>
                         </grade>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级" prop="classId">
                            <getClass v-model="formInline.classId" 
                            :isDefaultFill='isDefaultFillClass' 
                             @defaultFillClass='defaultFillClass'
                            :grade='formInline.gradeId'
                             ></getClass>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8"> 
                        <el-button type="primary" @click="onSubmit('formInline')">查询</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button  @click="updatePicEvent">上传图片</el-button>
                </div>
            </div>
            <el-table :data="queryData" style="width: 100%" border  v-loading="loading" ref="multipleTable">
                <el-table-column label="名称" prop="sName" align="center">
                     <template scope="scope">
                         {{scope.row|filterName}}
                    </template>
                </el-table-column>
                <el-table-column label="类型" align="center" prop="sType">
                    <template scope="scope">
                         {{scope.row.sType=='0'?'图片':'视频'}}
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="sStatus">
                    <template scope="scope">
                         {{scope.row.sStatus =='0'?'上线':'下线'}}
                    </template>
                </el-table-column>
                <el-table-column label="上传时间" align="center" prop="sCreateTime">
                    <template scope="scope">
                         {{scope.row.sCreateTime || '--'}}
                    </template>
                </el-table-column>
               <el-table-column align="left" label="操作" width="230px">
                    <template scope="scope">
                        <el-button type="text" class="btn-success"  @click="onlineOrDown(scope.row)">
                            {{scope.row.sStatus=='1'?'上线':'下线'}}
                        </el-button>
                        <el-button  type="text" class="btn-success"
                         @click="check(scope.row)">查看</el-button>
                        <el-button type="text" class="btn-success" v-if="scope.row.sStatus=='1'"
                         @click="deleteListOne(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listQuery.total"
                    :current-page.sync="listQuery.page"
                    :page-sizes="config.pageSizes"
                    :page-size="config.pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <el-dialog :visible.sync="dialogUpdatePic" title="上传图片" size="tiny" :before-close="handleClosePic"> 
            <el-form ref="updatePic" :model="updatePic" label-width="105px" :rules="rulesPic" >
                <el-form-item label="图片名称" prop="updatePicName">
                  <el-popover placement="top-start" trigger="focus"
                              content="字符长度不大于16位,不得含有空格">
                     <el-input v-model="updatePic.updatePicName" placeholder="请输入图片名称" slot="reference" @change='changeImage' :maxlength="16" style="width:90%"></el-input>
                  </el-popover>
                </el-form-item>
                <el-form-item label="上传图片" prop="updatePicAdress">
                    <el-row type="flex" class="row-bg">
                        <el-col :span="10">
                            <img-upload v-model="updatePic.updatePicAdress" :imageSize="2" @getImgName="getImgName" 
                            :showFileName="true"></img-upload>
                        </el-col>
                        <el-col :span="10" :offset="1" class="img-notation">
                            <p>推荐尺寸：1370*560</p> 
                            <p>支持png、jpg、bmp等不大于2M的照片</p>
                        </el-col>
                    </el-row>
                    
                </el-form-item>
                <el-row type="flex" class="row-bg" justify="center">
                    <el-col :span="4">
                        <el-button type="primary" @click="uploadPic('updatePic')" v-loading="uplaoPicLoading">上传</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
        <el-dialog :title="checkTitle" :visible.sync="dialogFormVisible" size="tiny" :before-close="handleCloseCheck">
            <div class='checkImg' v-if="checkStatus"><img :src="bigImgUrl"/></div>
            <div class='checkImg' v-if="!checkStatus"><video :src="movieUrl" controls="true" controlslist="nodownload"></video></div>
        </el-dialog>
    </div>
</template>

<script>
// import { getWisdomRatingHead, pageWisdomRating} from 'api/wisdom';
import TableLayout from 'components/TableLayout';
import fileUpload from 'components/Upload/fileUpload';
import school from 'components/SchoolClasss/school';
import getClass from 'components/SchoolClasss/class1';
import imgUpload from 'components/Upload/imgUpload2';
import { mapState, mapActions, mapGetters } from 'vuex';
import grade from 'components/SchoolClasss/grade';
import { saveAreaPic, pageAreaPic, updatePicStatus, deletePic, getAreaVideo, getPicOnline} from 'api/wisdom';
// import moment from 'moment';
export default{
    components: {TableLayout, school, getClass, imgUpload, fileUpload, grade},
    data() {
        var validat = (rule, value, callback) => {
            callback();
        };
        return {
            isDefaultFillClass: true, // 是否默认填充班级
            uplaoPicLoading: false,
            uplaoVideoLoading: false,
            dialogFormVisible: false,
            checkStatus: true,
            dialogUpdateImg: false,
            bigImgUrl: '',
            movieUrl: '',
            checkTitle: '',
            formInline: {// form表单数据
                classId: '',
                gradeId: ''
            },
            queryData: [],
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            fileOptions: {
                fileList: [],
                fileListShow: '',
                listType: 'video',
                upFileType: 'video',
                accept: ''
            },
            updatePic: {
                updatePicName: '',
                updatePicAdress: '',
                uplaoPicName: '',
                status: true
            },
            updateVideo: {
                updateVideoName: '',
                updateVideoAdress: ''
            },
            dialogUpdatePic: false,
            dialogUpdateVideo: false,
            loading: false,
            progress: false,
            rules: {
                gradeId: [
                    {required: true, message: '请选择年级', trigger: 'blur'}
                ],
                classId: [
                    {required: true, message: '请选择班级', trigger: 'blur'}
                ]
            },
            rulesPic: {
                updatePicName: [
                    { pattern: /^[^\s]+$/, message: '请勿输入空格', trigger: 'blur' }
                ],
                updatePicAdress: [
                    { required: true, validator: validat, trigger: 'change'}
                ]
            },
            onOff: true
        }
    },
  
    filters: {
        filterName(val) {
            if (!val.sName) {
                return val.sUrl.split('/')[val.sUrl.split('/').length-1].substring(0, 16)
            } else if (val.sName) {
                if (val.sName.length>10) {
                    return val.sName.substring(0, 16)
                } else {
                    return val.sName
                }
            }
        }
    },
    created() {
        // setTimeout(() => {
        //     if (this.formInline.gradeId&&this.formInline.classId) {
        //         this.searchFetchData();
        //     }
        // }, 500)
    },
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
        }),
        ...mapGetters([
            'schoolId',
            'schoolType'
        ])
    },
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val && this.searchFetchData();
        },
        'formInline.classId': {
            handler(oldVal, newVal) {
                if (oldVal) {
                    if (this.onOff) {
                        this.searchFetchData();
                        this.onOff = false;
                        this.isDefaultFillClass=false;
                    }              
                }
            },
            immediate: true
            
        }
    },
    methods: {
        // 全局获取行数
        ...mapActions(['ChangePageSize']),
        getImgName(name) {
            this.updatePic.uplaoPicName=name;
            if (this.updatePic.status) {
                this.updatePic.updatePicName=name.split('.')[0].substring(0, 16);
            }
        },
        defaultFillGrade(gradeId) {
            this.formInline.gradeId=gradeId;
        },
        defaultFillClass(classId) {
            this.formInline.classId=classId;
        },
        changeImage(a) {
            if (a) {
                this.updatePic.status = false;
            } else {
                this.updatePic.status = true;
            }
        },
        getVideoName(file) {
            this.updateVideo.updateVideoName=file.name.split('.')[0];
            this.updateVideo.updateVideoAdress=file.response.content.accessUrl;
        },
        handleClosePic() {
            this.delPicDiaogDate();
        },
         // 上线还是下线
        onlineOrDown(row) {
            let pId=row.pId,
                fSchoolId=row.fSchoolId,
                fClassId=row.fClassId,
                sAreaType= '0', // （sAreaType：0为班级风采，1为荣誉墙）
                warnTitle=row.sStatus=='1'?'确定上线？':'确定下线？',
                successTitle=row.sStatus=='1'?'已上线':'已下线';
            if (row.sType == '1' && row.sStatus=='1' && this.dialogUpdateImg) {
                warnTitle = '确认上线视频则将下线所有图片，图片和视频不可同时上线';
            }
            this.$confirm(warnTitle, ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                let json={
                    pId,
                    fClassId,
                    fSchoolId,
                    sAreaType
                }
                this.loading=true;
                updatePicStatus(json).then(res => {
                    this.searchFetchData();
                    this.$message.success(successTitle);
                }).catch(() => {
                    this.loading=false;
                })
            }).catch(() => {
                this.$message.info('已取消操作')
            });
        },
      
          // 查询列表
        searchFetchData() {
            this.loading = true;
            let json={
                fClassId: this.formInline.classId,
                fSchoolId: this.schoolId,
                page: this.listQuery.page,
                rows: this.config.pageSize,
                sAreaType: '0' // 0为班级风采，1为荣誉墙
            }
            pageAreaPic(json).then(response => {
                this.loading = false;
                this.isDefaultFillClass=false;
                if (response.data.content) {
                    this.queryData = response.data.content.list;
                    this.listQuery.total = response.data.content.pagination.total;
                }          
            }).catch(() => {
                this.loading = false;
            });
           
        },
        
              // 单个删除
        deleteListOne(row) {
            this.$confirm('确定删除？', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: ' ', // warning
                title: '  '
            }).then(() => {
                this.loading = true;
                this.detele(row.pId);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        onProgress(a) {
            this.progress = false;
            if (a.status=='success') {
                this.progress = true;
            }
        },
         // 删除
        detele(pId) {
            let json={
                pId
            }
            deletePic(json).then(res => {
                this.$message.success('已删除!')
                this.searchFetchData();
            }).catch(() => {
                this.loading=false
            });
        },
        // 文件名的截取那里:.split('.')[0] 需要改进 scyy
        // 上传图片
        uploadPic() {
            this.$refs.updatePic.validate((valid) => {
                if (valid) {// 验证通过
                    if (!this.formInline.classId) {
                        this.$message.info('请先选择班级')
                    } else if (this.updatePic.updatePicAdress=='') {
                        this.$message.info('请上传图片')
                    } else {
                        this.uplaoPicLoading=true;
                        let json={
                            fClassId: this.formInline.classId, 
                            fSchoolId: this.schoolId, 
                            sName: this.updatePic.updatePicName?this.updatePic.updatePicName:this.updatePic.uplaoPicName.split('.')[0],
                            sType: '0',
                            sUrl: this.updatePic.updatePicAdress,
                            sAreaType: '0' // 0为班级风采，1为荣誉墙
                        }
                        saveAreaPic(json).then(res => {
                            this.uplaoPicLoading=false;
                            this.$message.success('上传图片成功！');
                            this.searchFetchData();
                            this.delPicDiaogDate();
                        }).catch(() => {
                            this.uplaoPicLoading=false
                        })
                    }
                } else {
                    return false;
                }
            });
          
        },
    // 上传视频
        confirmVideo() {
            if (!this.formInline.classId) {
                this.$message.info('请先选择班级')
            } else if (this.updateVideo.updateVideoAdress=='') {
                this.$message.info('请上传视频')
            } else if (!this.progress) {
                this.$message.info('视频正在上传中');
                return;
            } else {
                this.uplaoVideoLoading=true;
                let fClassId=this.formInline.classId, 
                    fSchoolId=this.schoolId, 
                    sName=this.updateVideo.updateVideoName?this.updateVideo.updateVideoName:this.updateVideo.updateVideoName.split('.')[0],
                    sType='1',
                    sUrl=this.updateVideo.updateVideoAdress;
                saveAreaPic(fClassId, fSchoolId, sName, sType, sUrl).then(res => {
                    this.uplaoVideoLoading=false;
                    this.$message.success('上传视频成功！');
                    this.dialogUpdateVideo = false;
                    this.handleCloseVideo();
                    this.searchFetchData();
                    this.delVideoDiaogDate();
                }).catch(() => {
                    this.uplaoVideoLoading=false
                })
            }
        },
        // 关闭弹窗
        handleCloseVideo() {
            this.dialogUpdateVideo = false;
            this.uplaoVideoLoading=false;
            this.updateVideo.updateVideoName='';
            this.updateVideo.updateVideoAdress='';
            // this.$refs.fileUpload.clearFiles();
        },
        // 清除图片弹窗的数据
        delPicDiaogDate() {
            this.updatePic.updatePicAdress='';
            this.updatePic.updatePicName='';
            this.updatePic.status=true;
            this.dialogUpdatePic = false;
            this.uplaoPicLoading=false;
        },
      
        // 表单查询
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.searchFetchData();
                    this.handleCloseVideo();
                }
            });
        },
        // 点击上传图片
        updatePicEvent() {
            
            this.dialogUpdatePic = true;
        },
    //   点击上传视频
        updateVidioEvent() {
            let fClassId=this.formInline.classId, 
                fSchoolId=this.schoolId, 
                sType='1';
            getAreaVideo(fClassId, fSchoolId, sType).then(res => {
                if (res.data.content) {
                    this.dialogUpdateVideo = true;
                }
            })
        },
        check(row) {
            this.dialogFormVisible = true;
            if (row.sType=='0') {
                this.checkTitle = '查看图片';
                this.checkStatus = true;
                this.bigImgUrl = row.sUrl;
            } else {
                this.checkTitle = '查看视频';
                this.checkStatus = false;
                this.movieUrl = row.sUrl;
            }
        },
        handleCloseCheck() {
            this.dialogFormVisible = false;
            this.movieUrl = ''
        },
        fileFileRemove() {
            this.updateVideo.updateVideoName='';
            this.updateVideo.updateVideoAdress='';
            this.$refs.fileUpload.clearFiles();
        },
        fileSuccessFn() {
            // this.$message('上传成功！');
            // this.updateVideo.sVideoUrl = obj.imgUrl;
            // this.$refs.updateVideo.validateField('sVideoUrl');
        },
         // 分页
        handleSizeChange(val) {
            this.listQuery.page = 1;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {            
            this.listQuery.page = val;
            this.searchFetchData();
        }

    }
}
</script>
<style lang="scss" scoped>
.content {
    position: relative;
    padding: 0px;
    $bgcolor:#fff;
    .bos-file-uplader-component-container {
        overflow: visible;
        height: auto;
        .up-container {   
            text-align: left;   
        }
        .up-container.border-style {
            border: 1px dashed #c0ccda;
            border-radius: 6px;
        }
    }
    .img-notation{
        padding-top: 30px;
    }
    label{
        text-align:left;
    }
    .formInline {
        .formBtn{
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition{
                position: absolute;
                right:0px; 
                top: 18px;
            }
        }
    }
    .checkImg{
        width:100%;
        height:280px;
        img{
            width:100%;
            height:100%;
        }
        video{
            width:100%;
            height:100%;
        }
    }
    .btnPosition {
        float:right;
    }
    .el-dialog__wrapper{
        z-index:3000 !important;
    }
}
</style>